<template>
<HeaderComponent />
<div id="BackLink">
      <router-link :to="{name:'Main'}">Return to Main Menu</router-link>
</div>
<div id="Catalog">
      <form @submit.prevent="handleSubmit">
        <p v-if="signOnMsg" style="color:red;">{{ signOnMsg }}</p>

        <table class="signOnTable">
        <tbody>
          <tr>
            <td>
              <div class="input-icon-group">
                <input type="text" v-model="username" placeholder="Username:" />
                <img :src="usernameImg" class="icon" />
              </div>
            </td>
          </tr>

          <tr>
            <td>
              <div class="input-icon-group">
                <input type="password" v-model="password" placeholder="Password:" />
                <img :src="codeImg" class="icon" />
              </div>
            </td>
          </tr>

          <tr>
            <td>
              <div class="verify-container">
                <div class="input-icon-group">
                <input type="text" 
                v-model="verificationCode" 
                placeholder="Verification:" 
                class="verification-input"
                />
                <img :src="verImg" class="icon" />
              </div>
                <img 
                class="verify" 
                :src="'data:image/png;base64,' + imgByte"
                alt="验证码"
                @click="getCaptcha"
                />
              </div>
            </td>
          </tr>
        </tbody>
        </table>
        <div id="third-party-login" >
          <button @click="getGiteeAuthCode">使用 Gitee 登录</button>
        </div>
        <input type="submit" value="login" />
      </form>
      <p>
        Need a user name and password?
        <router-link :to="{name:'Register'}">Register Now!</router-link>
      </p>
      <br><br><br><br><br><br><br><br><br>
</div>
<FooterComponent />
</template>
<script setup>
import { ref, onMounted } from 'vue';
import HeaderComponent from '@/components/Header.vue';
import FooterComponent from '@/components/Footer.vue';
import { login, loginWithGitee, getVerificationCode } from '@/api/account.js'; 
import { useRoute,useRouter } from 'vue-router';
import { useAccountStore } from '@/stores/accountStore';

// 图片
const usernameImg = new URL('@/assets/images/username.png', import.meta.url).href;
const codeImg = new URL('@/assets/images/code.png', import.meta.url).href;
const verImg = new URL('@/assets/images/ver.png', import.meta.url).href;


//第三方登陆
const router = useRouter();

//路由跳转
const route = useRoute();

//登陆信息
const username = ref('');
const password = ref('');

const verificationCode = ref('');
const verificationCodeToken = ref('');
const imgByte = ref('');

const signOnMsg = ref('');

// 状态管理
const accountStore = useAccountStore();


// 登录功能
async function handleSubmit() {
  if (!username.value || !password.value) {
    signOnMsg.value = '请输入用户名和密码';
    return;
  }

  if (!verificationCode.value || !verificationCodeToken.value) {
    signOnMsg.value = '请输入验证码';
    return;
  }
  try {
    console.log('准备提交的数据：', {
  username: username.value,
  password: password.value,
  verificationCode: verificationCode.value,
  verificationCodeToken: verificationCodeToken.value  // 加入验证码令牌
  });
    const response = await login({
      username: username.value,
      password: password.value,
      verificationCode: verificationCode.value,
      verificationCodeToken: verificationCodeToken.value
    });
    console.log('登录完整响应：', response);
    console.log('response.status 是：', response.status);
    if (response.status === 0) {
      console.log('登录成功,后端返回的data:', response.data);
      localStorage.setItem('token', response.data.token);
      localStorage.setItem('username', response.data.username);
      //状态更新
      accountStore.login(response.data.token, response.data.username); 
      // 清除 query 参数，避免用户刷新或返回时重复授权
      router.replace({ path: '/signon' });
      router.push('/main');
    } else {
      console.log('登录失败：！！！', response.message);
      signOnMsg.value = response.message || '登录失败';
    }
  } catch (error) {
    console.error('请求异常：',error);
    signOnMsg.value = error.response?.message || '服务器异常，请稍后再试';
  }
}

// Gitee 第三方登录功能
onMounted(() => {
  // const code = route.query.code;
  const token = route.query.token;
  const username = route.query.username;
  if (token && username) {
    console.log('检测到 token',token,'  username',username);
    // handleGiteeLogin(code);
    localStorage.setItem('token', token);
    localStorage.setItem('username', username);
    accountStore.login(token, username);
    router.push('/main'); // 登录成功
  }
});

//用不上，只是方便收缩
async function handleGiteeLogin(code) {
    try {
      const response = await loginWithGitee(code);
      console.log('gitee response',response);
      if (response.status === 0) {
        console.log('Gitee 登录成功', response.data);
        localStorage.setItem('token', response.data.token);
        localStorage.setItem('username', response.data.username);
        //状态更新
        accountStore.login(response.data.token, response.data.username);
        router.push('/main');
      } else {
        signOnMsg.value = response.message || 'Gitee 登录失败';
      }
    } catch (error) {
      console.error('Gitee 登录异常', error);
      signOnMsg.value = error.response?.message || '服务器异常，请稍后再试';
    }
}

// 获取验证码
async function getCaptcha() {
  try {
    const response = await getVerificationCode();
    console.log('verification response', response)
    if (response && response.status === 0 && response.data) {
      verificationCodeToken.value = response.data.verificationCodeToken;
      imgByte.value = response.data.imgByte;  // 设置验证码图片
    } else {
      const msg = response?.message || '验证码获取失败';
      console.error('验证码获取失败:', msg);
      signOnMsg.value = msg;
    }
  } catch (error) {
    console.error('获取验证码失败:', error);
    signOnMsg.value = '获取验证码失败，请稍后重试';
  }
}


// 刷新验证码
function refreshCaptcha() {
  console.log('刷新验证码');
  getCaptcha();
}

// 组件挂载时获取验证码
onMounted(() => {
  getCaptcha();
});

//  Gitee 授权码
function getGiteeAuthCode() {
const clientId = 'c56e9f38cfb90df69c93970e2b3d01f04e821fa19ebf1d8774b93ebd15a5d014';  // 客户端 ID
const redirectUri = encodeURIComponent('http://localhost:8080/api/user/auth/gitee');  // 替换为你的回调地址
// const scope = 'user_info';  // 根据需求选择授权范围，'user_info' 获取基本用户信息

// 构建授权链接
const authUrl = `https://gitee.com/oauth/authorize?client_id=${clientId}&redirect_uri=${redirectUri}&response_type=code`;

// 重定向到 Gitee 登录页面
window.location.href = authUrl;
console.log('回调authurl:',authUrl);
}
</script>

<style scoped>
.error-message {
  color: red;
  font-size: 12px;
  text-align: center;
}

#third-party-login {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

button {
  display: block;
  width: 120px;
  /* padding: 10px; */
  color: white;
  border: none;
  border-radius: 5px;
  /* margin-top: 10px; */
  text-align: center;
  height: 25px;
  background-color: #f1c48f;
  text-shadow: -2px 2px 2px rgb(209 132 0);
  box-shadow: 2px 2px 0px 0px #f39c12;
  transition: all .5s;
  display: flex;
  justify-content: center;
}

button:hover {
  background-color:#fcdc5e;
}

.signOnTable {
  width: 100%;
  max-width: 300px;
  margin: 0 auto;
}
.signOnTable .icon {
    /* width: 32px;
    height: 32px; */
    position: absolute;
    /* left: 2px; */
    /* top: 12px; */
    background-color: #eaac00;
}
.input-icon-group {
  display: flex;
  align-items: center; /* 垂直居中对齐 */
}
.input-icon-group input {
  flex: 1; /* 让 input 占据主空间 */
}
.icon {
  width: 20px;
  height: 20px;
  margin-left: 10px;
  vertical-align: middle;
}

.ver {
  width: 100px;
  height: 30px;
  margin-left: 10px;
  cursor: pointer;
}

input[type="submit"] {
  background-color: #f1c48f;
  color: white;
  /* padding: 10px 20px; */
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
  margin-top: 20px;
  width: 120px;
  max-width: none;
}

input[type="submit"]:hover {
  background-color: #fcdc5e;
}

.verify-container {
  display: flex;
  align-items: center;
  gap: 10px; /* 控制子元素之间的间距 */
}

.verification-input {
  width: 160px; /* 可按需调整 */
}

.icon {
  width: 24px;
  height: 24px;
}

.verify {
  width: 80px;
  height: 32px;
  cursor: pointer;
  /* border: 1px solid #ccc; */
  border-radius: 4px;
}
</style>

